package com.prs.crm.service.stock.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.context.Constrains;
import com.prs.crm.dao.stock.StoreOutDao;
import com.prs.crm.domain.flow.WorkFlowProcess;
import com.prs.crm.domain.stock.Product;
import com.prs.crm.domain.stock.ProductStore;
import com.prs.crm.domain.store.StoreOut;
import com.prs.crm.domain.store.StoreOutDetail;
import com.prs.crm.domain.store.StoreRoom;
import com.prs.crm.service.impl.FlowServiceImpl;
import com.prs.crm.service.stock.ProductStoreService;
import com.prs.crm.service.stock.StoreOutService;

public class StoreOutServiceImpl extends FlowServiceImpl<StoreOut, StoreOutDao>
		implements StoreOutService {
	
	@Autowired
	private ProductStoreService productStoreService;
	
	

	@Override
	public ProductStore getStore(StoreRoom room, Product product) {
		
		return this.getDao().getStore(room, product);
	}

	@Override
	public void saveAll(StoreOut storeout, StoreRoom[] rooms,Product[] products, Integer[] storeoutNums,String[] name,Integer[] id) {
		for(int i=0;i<products.length;i++){
			/*ProductStore  pspo=this.getProductStoreService().getStore(rooms[i], products[i],storeout.getBatchNum());
			pspo.setProductNum(pspo.getProductNum()-storeoutNums[i]);
		    this.getProductStoreService().savePrStore(pspo);*/
		    StoreOutDetail   outdetails=new StoreOutDetail();
		    outdetails.setName(name[i]);
		    outdetails.setProduct(products[i]);
		    outdetails.setRoom(rooms[i]);
		    outdetails.setStoreoutNum(storeoutNums[i]);
		    storeout.addDetail(outdetails);
		    }
		super.save(storeout);
		
	}

	@Override
	public void onProcessEnd(WorkFlowProcess process) {
	
		super.onProcessEnd(process);
		StoreOut storeOut=this.getProcessEntity(process);
		
		Set<StoreOutDetail> outDetails=storeOut.getOutdetails();
		if(process.getResult()==Constrains.WORKFLOWPROCESS_RESULT_PASS){
			for(StoreOutDetail outDetail:outDetails){
				ProductStore  pspo=this.getProductStoreService().getStore(storeOut.getRoom(), outDetail.getProduct(),storeOut.getBatchNum());
				pspo.setProductNum(pspo.getProductNum()-outDetail.getStoreoutNum());
			    this.getProductStoreService().savePrStore(pspo);
			}
		}else{
			
		}
	}

	@Override
	public boolean valideSubmit(StoreOut entity) {
		
		return true;
	}
	
	public ProductStoreService getProductStoreService() {
		return productStoreService;
	}

	public void setProductStoreService(ProductStoreService productStoreService) {
		this.productStoreService = productStoreService;
	}

}
